package marcis.jarina.web.controller;

import marcis.jarina.db.hibernate.entities.Archive;
import marcis.jarina.db.hibernate.entities.JavaClass;
import marcis.jarina.db.services.DefaultArchiveService;
import marcis.jarina.db.services.DefaultJavaClassService;
import marcis.jarina.web.gui.entity.WrappedList;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@SuppressWarnings({"SpringJavaAutowiringInspection"})
@Controller
@RequestMapping(value = "/search")
public class SearchController {

    private static final Logger logger = Logger.getLogger(SearchController.class);

    @Autowired
    private DefaultArchiveService defaultArchiveService;

    @Autowired
    private DefaultJavaClassService classServiceDefault;

    @RequestMapping(value = "/result.html", method = RequestMethod.POST)
    public ModelAndView displaySearchResult(HttpServletRequest request, HttpServletResponse response) {
        String className = request.getParameter("className");
        List<JavaClass> classList = classServiceDefault.pagedFilter("fullName", className, 0, WrappedList.PER_PAGE);
        List<Archive> archiveSet = createList(classList);
        ModelAndView modelAndView = new ModelAndView("searchResult");
        modelAndView.addObject("list", WrappedList.getWrappedList(archiveSet, 0));
        return modelAndView;
    }

    private List<Archive> createList(final Collection<JavaClass> classList) {
        final List<Archive> resultList = new ArrayList<Archive>();
        for (JavaClass javaClass : classList) {
            resultList.add(javaClass.getArchive());
        }
        return resultList;
    }

    /*
    @RequestMapping(value = "/result/{page}.html", method = RequestMethod.GET)
    public ModelAndView displaySearchResltPage(@PathVariable("className") String className, @PathVariable("page") int page) {
        List<Archive> list = defaultArchiveService.getPagedList(Archive.class, page * WrappedList.PER_PAGE, WrappedList.PER_PAGE);
        ModelAndView modelAndView = new ModelAndView("searchResult");
        modelAndView.addObject("list",  WrappedList.getWrappedList(list, page));
        return modelAndView;
    }
    */
}
